import React, { useEffect, useState, useRef } from 'react';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { t } from '@lingui/macro';
import { Button, Dialog, Drawer, Message, Checkbox, Tab } from '@alifd/next';
import { useStore } from '@/hooks';
import { uniqueId } from 'lodash';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import CouponsTable from './components/CouponsTable';
import PartnerDrawer from './components/PartnerDrawer';

const tableId = uniqueId('tauTable-');
const { confirm } = Dialog;

function Customer({ inviteCodes }) {
  const { customerStore: store } = useStore();
  const [userType, setUserType] = useState([]);
  const [showOrders, setShowOrders] = useState(false);
  const [showCoupons, setShowCoupons] = useState(false);
  const [counts, setCounts] = useState();
  const [couponsCounts, setCouponsCounts] = useState();
  const [modal, setModal] = useState([]);
  const customerRef = useRef();

  useEffect(() => {
    (async () => {
      const typeList = await store?.getType('customerType');
      setUserType([...typeList]);
    })();
  }, []);

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const res = await fetchOrderCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showOrders, store.customers]);

  useEffect(() => {
    if (showCoupons) {
      (async () => {
        const res = await fetchCouponsCounts();
        setCouponsCounts(res);
      })();
    } else {
      setCouponsCounts([]);
    }
  }, [showCoupons, store.customers]);

  const fetchOrderCounts = async () => {
    const promiseAry = store.customers.map((p) => {
      const { username, id } = p;
      const search = {
        username,
      };
      const promise1 = store.api.busOrderCount({ search });

      const promise2 = store.api.scOrderCount({ search });

      const promise3 = store.api.ccOrderCount({ search });

      return Promise.all([promise1, promise2, promise3])
        .then((results) => ({
          id,
          counts: results,
        }));
    });
    return Promise.all(promiseAry);
  };


  // 获取订单
  async function fetchCouponsCounts() {
    const promiseAry = store.customers.map(async (p) => {
      return store.api.getCouponCount({
        search: {
          username: p.username,
        },
      }).then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }

  /**
   * @description 处理搜索条件
   * @param {*} params
   */
  const handleOnSearch = (params) => {
    const { getOnDate, getOnLastTime, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    const [lastLoginFrom, lastLoginTo] = getOnLastTime || [];
    store.search = {
      from,
      to,
      lastLoginFrom,
      lastLoginTo,
      ...searchArgs,
      inviteCodes,
    };
  };

  /**
   * @description 打开卡片
   */
  const handleOpenEdit = (r) => {
    customerRef.current = r;
    setModal(['edit']);
  };

  /**
   * @description 删除客户事件回掉函数
   * @param {*} r
   * @returns true
   */
  // eslint-disable-next-line no-unused-vars
  const handleDeleteUser = (r) => {
    confirm({
      title: '确认删除该客户吗?',
      onOk() {
        return store.deleteUser(r);
      },
    });
  };

  /**
   * @description 启用和禁用用户
   * @param {*} r
   * @returns true
   */
  const handleUpdateStatus = (r) => {
    confirm({
      title: `确认${ENUMS.status[r.status]}该客户吗?`,
      onOk() {
        const args = {
          username: r.username,
          status: r.status === 0 ? 1 : 0,
        };
        return store.update({ ...args });
      },
    });
  };

  /**
   * @description 更新用户
   * @param {*} result
   * @returns true
   */
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  /**
   * @description 发放卡券
   * @param {*} result
   * @returns true
   */
  const sendCouponSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.sendCoupon(toJS(result));
        Message.success({ content: t`发放成功` });
      } catch (e) {
        Message.error({ content: t`发放失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleCancel = () => {
    setModal({ visible: false });
  };

  // 查看包车订单
  const handleOpenCCOrder = (result) => {
    customerRef.current = result;
    setModal(['ccOrder']);
  };

  // 查看专线订单
  const handleOpenSCOrder = (result) => {
    customerRef.current = result;
    setModal(['scOrder']);
  };

  // 查看巴士订单
  const handleOpenBusOrder = (result) => {
    customerRef.current = result;
    setModal(['busOrder']);
  };

  // 查看详情
  const handleOpenView = (result) => {
    customerRef.current = result;
    setModal(['view']);
  };

  // 查看巴士订单
  const handleOpenCoupons = (result) => {
    const { username } = result;
    customerRef.current = { username };
    setModal(['coupons']);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`注册开始时间`, t`注册结束时间`],
            },
          },
          {
            name: 'getOnLastTime',
            type: 'date-range',
            props: {
              placeholder: [t`登陆开始时间`, t`登陆结束时间`],
            },
          },
          {
            name: 'status',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.state),
              placeholder: t`状态`,
            },
          },
          {
            name: 'customerType',
            type: 'select',
            props: {
              dataSource: userType,
              placeholder: t`区域类型`,
              style: { width: 180 },
            },
          },
          {
            name: 'sourceType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.type),
              placeholder: t`来源类型`,
              style: { width: 180 },
            },
          },
          {
            name: 'hasPhoneNumber',
            type: 'select',
            props: {
              dataSource: [
                { label: t`是`, value: true },
                { label: t`否`, value: false },
              ],
              placeholder: t`绑定手机号`,
              style: { width: 120 },
            },
          },
        ]}
        extraItems={[
          {
            name: 'cbx-showOrders',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowOrders(v)}>{t`查看订单`}</Checkbox>,
          },
          {
            name: 'cbx-showCoupons',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowCoupons(v)}>{t`查看卡券`}</Checkbox>,
          },
        ]}
        keywordSearch={{
          // enabled: false,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.customers)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('username', {
              width: 200,
              cell: (v, _, customer) => <Button type="primary" text onClick={() => handleOpenView(customer)}>{v}</Button>,
            }),
            column('fullname', { width: 98 }),
            column('mobile', { width: 110 }),
            column('busOrder', {
              width: 70,
              cell: (v, _, customer) => <Button type="primary" text onClick={() => handleOpenBusOrder(customer)}>{counts.find((c) => c.id === customer.id)?.counts[0] || 0}</Button>,
            }),
            column('specialCarOrder', { width: 70, cell: (v, _, customer) => <Button type="primary" text onClick={() => handleOpenCCOrder(customer)}>{counts.find((c) => c.id === customer.id)?.counts[2] || 0}</Button> }),
            column('shuttleBusOrder', { width: 70, cell: (v, _, customer) => <Button type="primary" text onClick={() => handleOpenSCOrder(customer)}>{counts.find((c) => c.id === customer.id)?.counts[1] || 0}</Button> }),
            column('couponCount', {
              width: 70,
              cell: (v, _, customer) => <Button type="primary" text onClick={() => handleOpenCoupons(customer)}>{couponsCounts.find((c) => c.id === customer.username)?.count || 0}</Button>,
            }),
            column('rate', { width: 88 }),
            column('source', { width: 68 }),
            column('sourceType', {}),
            column('receiverName', {}),
            column('status', {}),
            column('customerInfo.registerTime', { width: 128, sortable: true }),
            column('lastLogin', { width: 128, sortable: true }),
            {
              title: t`操作`,
              dataIndex: 'customerNumber',
              width: 160,
              cell: (_, __, customer) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(customer)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  {/* <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDeleteUser(customer)} >{t`删除`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span> */}
                  <Button text type="primary" style={{ color: 'green' }} onClick={() => handleUpdateStatus(customer)} >{t`${ENUMS.status[customer.status]}`}</Button>
                </>),
            },
          ]
            .filter((c) => (c.dataIndex !== 'busOrder' || showOrders) && (c.dataIndex !== 'specialCarOrder' || showOrders) && (c.dataIndex !== 'shuttleBusOrder' || showOrders) && (c.dataIndex !== 'showCoupons' || showCoupons))
            .filter((c) => c.dataIndex !== 'couponCount' || showCoupons)}
        />
      </div>
      <Drawer
        visible={modal[0] === 'coupons'}
        title={t`查看优惠券`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="70%"
      >
        <CouponsTable
          args={customerRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={sendCouponSubmit}
        />
      </Drawer>
      <PartnerDrawer data={customerRef.current} modal={modal} setModal={setModal} onCancel={handleCancel} onSubmit={handleUpdate} />
      <ComponentsDrawer modal={modal} queryParams={{ username: customerRef.current?.id }} name={customerRef.current?.fullname} onCancel={handleCancel} />
    </TauPage>
  );
}

export default observer(Customer);
